import React, { useState } from 'react'
import { Button } from '../ui/button'

interface Column {
  key: string
  label: string
}

interface SortableTableProps<T> {
  data: T[]
  columns: Column[]
  title?: React.ReactNode
  enemy?: boolean // 是否为敌方，false时只显示目标人物和职业
}

const SortableTable = <T,>({
  data,
  columns,
  title,
  enemy = true
}: SortableTableProps<T>) => {
  const [sortConfig, setSortConfig] = useState<{
    key: keyof T
    direction: 'ascending' | 'descending'
  } | null>(null)

  // 默认按第三列倒序排序（如果有第三列）
  React.useEffect(() => {
    if (columns && columns.length > 2) {
      setSortConfig({ key: columns[2].key as keyof T, direction: 'descending' })
    }
  }, [columns])

  const sortedData = React.useMemo(() => {
    if (sortConfig !== null) {
      return [...data].sort((a, b) => {
        const aValue = a[sortConfig.key]
        const bValue = b[sortConfig.key]

        if (typeof aValue === 'string' && typeof bValue === 'string') {
          const aStr = aValue || ''
          const bStr = bValue || ''
          return sortConfig.direction === 'ascending'
            ? aStr.localeCompare(bStr)
            : bStr.localeCompare(aStr)
        }

        if (aValue == null) return sortConfig.direction === 'ascending' ? -1 : 1
        if (bValue == null) return sortConfig.direction === 'ascending' ? 1 : -1

        if (aValue < bValue) {
          return sortConfig.direction === 'ascending' ? -1 : 1
        }
        if (aValue > bValue) {
          return sortConfig.direction === 'ascending' ? 1 : -1
        }
        return 0
      })
    }
    return data
  }, [data, sortConfig])

  const requestSort = (key: keyof T) => {
    let direction: 'ascending' | 'descending' = 'ascending'
    if (
      sortConfig &&
      sortConfig.key === key &&
      sortConfig.direction === 'ascending'
    ) {
      direction = 'descending'
    }
    setSortConfig({ key, direction })
  }

  // 导出名字文本功能
  const handleExportNames = () => {
    // 假设名字字段为 'name'
    const nameKey =
      columns.find((col) => col.label === '名字' || col.key === 'name')?.key ||
      'name'
    const names = sortedData
      .map((item) => String(item[nameKey as keyof T] ?? ''))
      .filter(Boolean)
      .join('\n')
    const blob = new Blob([names], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${title || 'names'}.txt`
    a.click()
    URL.revokeObjectURL(url)
  }

  // enemy为false时，仅显示目标人物和职业字段
  let displayColumns = columns
  if (enemy === false) {
    // 只保留label为'目标人物'或'职业'的列（或key为'target'/'profession'）
    displayColumns = columns.filter(
      (col) =>
        col.label === '玩家' ||
        col.label === '职业' ||
        col.key === 'target' ||
        col.key === 'profession'
    )
  }

  return (
    <div>
      {(title || true) && (
        <div className="mb-2 flex items-center justify-between gap-2">
          {title && (
            <div className="text-lg font-semibold text-gray-800">{title}</div>
          )}
          <Button
            variant={'ghost'}
            onClick={handleExportNames}
            className="shrink-0"
          >
            导出
          </Button>
        </div>
      )}
      <div className="overflow-x-auto rounded-lg border border-gray-200 bg-white shadow-md">
        <table className="min-w-full text-left text-sm">
          <thead>
            <tr>
              {displayColumns.map((column, idx) => (
                <th
                  key={column.key}
                  className={`group cursor-pointer select-none border-b border-gray-300 bg-gray-200 px-4 py-3 font-semibold text-gray-700 transition-colors duration-150 hover:bg-gray-100${
                    idx !== displayColumns.length - 1
                      ? ' border-r border-gray-300'
                      : ''
                  }`}
                  onClick={() => requestSort(column.key as keyof T)}
                >
                  <span className="flex items-center gap-1">
                    {column.label}
                    <span className="text-xs">
                      {sortConfig?.key === column.key ? (
                        sortConfig.direction === 'ascending' ? (
                          '▲'
                        ) : (
                          '▼'
                        )
                      ) : (
                        <span className="opacity-30">⬍</span>
                      )}
                    </span>
                  </span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sortedData.map((item, index) => (
              <tr
                key={index}
                className={
                  'transition-colors duration-150 ' +
                  (index % 2 === 0
                    ? 'bg-gray-50 hover:bg-gray-100'
                    : 'bg-white hover:bg-gray-50')
                }
              >
                {displayColumns.map((column, colIdx) => {
                  // enemy为true时，第三列（索引2）绿色，第四列（索引3）红色
                  let extraClass = ''
                  if (enemy === true) {
                    if (colIdx === 2) extraClass = ' bg-green-100'
                    if (colIdx === 3) extraClass = ' bg-red-100'
                  }
                  const value = item[column.key as keyof T]
                  let displayValue: string | number = ''
                  if (typeof value === 'number') {
                    displayValue = value.toLocaleString()
                  } else {
                    displayValue = String(value)
                  }
                  return (
                    <td
                      key={column.key}
                      className={`border-b border-gray-300 px-4 py-2 text-gray-700${extraClass}${
                        colIdx !== displayColumns.length - 1
                          ? ' border-r border-gray-300'
                          : ''
                      }`}
                    >
                      {displayValue}
                    </td>
                  )
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default SortableTable
